home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / The World of Computer Software.iso / mod2tutr.zip / CHAP04.TXT < prev    next >
Text File  |  1989-01-18  |  21KB  |  529 lines

  1.  
  2.                                                      Chapter 4
  3.  
  4.                                   LOOPS AND CONTROL STRUCTURES
  5.  
  6.  
  7.  
  8.  
  9. WHAT IS STRUCTURED PROGRAMMING?
  10. ______________________________________________________________
  11.  
  12. There is a lot of talk these days about structured
  13. programming, so we should know what it is.  Structured
  14. programming is really another way of saying, "do it right."
  15. Instead of using sloppy coding techniques, you should plan
  16. carefully what you are doing, and instead of using the goto
  17. statement profusely to produce "spaghetti code", you should
  18. use only sequential (statements in succession), iterative
  19. (looping), and decision (selective branching) statements.  It
  20. has been proven that any logic can be reduced to these three
  21. constructs, and that the goto is not required.  Modula-2
  22. forces you to very carefully think out your logic prior to
  23. beginning to code since it does not have a goto statement
  24. available.  Depending on your programming background, this may
  25. come as a bit of a shock to you, but you will find that as you
  26. learn to use Modula-2, you will not miss the goto statement.
  27.  
  28. Many books are available on structured programming and you
  29. would be advised to purchase one so you can study proper
  30. programming techniques before you embark on a major
  31. programming project.
  32.  
  33.  
  34.  
  35. REPEATING AND DECIDING
  36. ______________________________________________________________
  37.  
  38. Loops are some of the most important and most used constructs
  39. in computer programming and in all parts of your life.  You
  40. use loops all the time for many things.  Walking is a
  41. repetition of putting one foot in front of the other until you
  42. get where you are going.  Eating a sandwich involves a loop
  43. of eating, chewing, swallowing, etc.  In this chapter we will
  44. first cover all of the possible loops you can define in
  45. Modula-2, then go on to the control structures, the decision
  46. makers.
  47.  
  48. Examine the program LOOPDEMO.MOD.  This is    ================
  49. a rather large program compared to the          LOOPDEMO.MOD
  50. ones we have seen so far, but it is felt      ================
  51. that it would be better to cover all of
  52. the loops in one file than have you compile and run 4
  53. different files.
  54.  
  55.  
  56.  
  57.  
  58.                                                            4-1
  59.  
  60.                       Chapter 4 - Loops and Control Structures
  61.  
  62. THE REPEAT ... UNTIL LOOP
  63. ______________________________________________________________
  64.  
  65. Ignoring the declaration part of the listing and going
  66. straight to the program itself, we come first to the repeat
  67. loop which does just what it says it will do.  It will repeat
  68. until it is told to stop.  The reserved word REPEAT in line
  69. 16 and the reserved word UNTIL in line 19 go together, and
  70. everything between them will be executed until the condition
  71. following the UNTIL becomes true.  The condition can be any
  72. expression that will evaluate to a boolean answer, true or
  73. false.  It can even be a composite expression with AND's,
  74. OR's, and NOT's like we studied in the last chapter.  It can
  75. be composed of any of the simple types discussed so far as
  76. long as the terms are all compatible and it evaluates to a
  77. boolean value.  In this case we have a very simple expression,
  78. "Index = 5".  Since the variable named Index is initialized
  79. to 0 and is incremented each time we go through the loop, it
  80. will eventually reach a value of 5 and the loop will
  81. terminate, after which time the expressions following it will
  82. be executed.
  83.  
  84. We are not quite finished with the repeat loop yet, since we
  85. will have more to say about it when we complete the while
  86. loop.
  87.  
  88.  
  89. THE WHILE LOOP
  90. ______________________________________________________________
  91.  
  92. The while loop is very much like the repeat loop except that
  93. the condition is tested at the beginning of the loop and when
  94. the condition becomes false, the loop is terminated.  Once
  95. again, the condition can be as complex as desired but in this
  96. case it is the very simple "Index < 5" following the reserved
  97. word WHILE, in line 24, which will control the loop
  98. termination.  When Index reaches 5, the loop is terminated and
  99. the statements following the loop are executed.
  100.  
  101. The biggest difference between the repeat and the while loops
  102. is concerned with when the test is made.  In the while loop,
  103. the test is made at the beginning, so it is possible that the
  104.  
  105. statements inside the loop will not be executed even once.
  106. In the repeat loop, the test is made at the end of the loop,
  107. so the statements in the loop will always be executed at least
  108. once.  It is also good to keep in mind that the repeat stops
  109. when its condition goes true, and the while stops when its
  110. condition goes false.
  111.  
  112. There is another loop that we can use in which we exit from
  113. the center using any test we can devise.  It will be covered
  114. after we complete the FOR loop.
  115.  
  116.  
  117.                                                            4-2
  118.  
  119.                       Chapter 4 - Loops and Control Structures
  120.  
  121. THE FOR LOOP
  122. ______________________________________________________________
  123.  
  124. The for loop exists in one form or another in nearly every
  125. programming language and you will use it repeatedly because
  126. it is so useful.  It uses the reserved words FOR, TO, BY, DO,
  127. and END.  It uses any simple variable type except real, and
  128. counts loops depending on what counts you put in for beginning
  129. and ending points.  The first example on line 31 says for the
  130. computer to start Index at 1 and count to 5, going through the
  131. loop once for each value of Index.  The count advances by 1
  132. each time because nothing else is specified and 1 is the
  133. default.  The end of the loop is specified by the reserved
  134. word END in line 33 in this case, and as many statements as
  135. desired can be within the body of the loop.
  136.  
  137. The next loop starts in line 37 and this time counts  from 5
  138. to 25 but incrementing by 4 each time because of the "BY 4"
  139. part of the line.  The loop will continue until the second
  140. limit is either reached or is going to be exceeded, at which
  141. time the loop will stop.  The beginning and ending limits can
  142. themselves be some kind of a calculated value or a constant,
  143. the only provision being that they must be of the same type
  144. as the loop indexing variable.  In fact they can be negative
  145. and the increment value can be negative.  This is illustrated
  146. in the next loop that starts in line 48 where we count by -7
  147. until we go from 5 to -35.  No further explanation should be
  148. required for this loop.
  149.  
  150. The next loop, starting in line 54, uses calculated limits to
  151. determine its starting and ending points and it uses the
  152. constant named Where for its incrementing value.  The value
  153. of the constant Where is established in the definition part
  154. of this program as a constant.  It is simply used here and
  155. will be explained in a future lesson when we get to it.  Where
  156. is a constant with a value of 11, and the incrementing value,
  157. used in any for loop must always be a constant, but not
  158. necessarily a predefined constant as is used here.  It can be
  159. an implicit constant as illustrated in line 48.
  160.  
  161.  
  162. A CHARACTER TYPE LOOP CONTROL INDEX
  163. ______________________________________________________________
  164.  
  165. The next two for loops use a char type variable and simply
  166. count from A to Z, or backwards in the case of the second one.
  167. The observant student will note that we are incrementing or
  168. decrementing a char type variable each time we go through the
  169. loop.  Even though this is not permitted in assignment
  170. statements, it is permitted in this case.
  171.  
  172. Several things should be pointed out about the for loop for
  173. you.  The three values must agree in type, that is the index,
  174. the starting point, and the ending point.  The index must not
  175.  
  176.                                                            4-3
  177.  
  178.                       Chapter 4 - Loops and Control Structures
  179.  
  180. be changed by any logic within the loop or the results will
  181. be unpredictable.
  182.  
  183. The value of the index must be assumed to be undefined after
  184. the loop terminates.  You may discover that it is predictable
  185. on your compiler, but it may not be on some other compiler,
  186. and you may want to transfer your program to another system
  187. someday, so if you find that the value is predictable, you
  188. should not make use of that knowledge.
  189.  
  190.  
  191. SUMMARY OF FOR LOOP RULES
  192. ______________________________________________________________
  193.  
  194. Since the for loop is so important, a practical list of usage
  195. rules are given as follows;
  196.  
  197. 1.   You cannot alter the value of the index variable within
  198.      the loop.
  199.  
  200. 2.   The bounds and increment expressions should not depend
  201.      on anything within the body of the loop.
  202.  
  203. 3.   The value of the index variable is undefined following
  204.      loop termination.
  205.  
  206. 4.   The loop index cannot be;
  207.        a.  An imported variable
  208.        b.  A member of a record, array, or set
  209.        c.  A real variable
  210.        d.  A procedure formal parameter
  211.  
  212. The compiler will detect most of these violations and report
  213. an error, but all compilers will not detect all of these
  214. errors.  You will understand all parts of rule 4 after you
  215. complete this entire tutorial.
  216.  
  217.  
  218. THE INFINITE LOOP
  219. ______________________________________________________________
  220.  
  221. The fourth and final loop is an infinite loop as illustrated
  222. in lines 77 through 87.  It uses the reserved words LOOP and
  223. END, and it never terminates by itself.  It is up to you the
  224. programmer to see to it that some means of terminating it is
  225. available, the most usual is through use of the exit
  226. statement.  Anyplace in the loop you can set up some
  227. conditions for exiting based on whatever you desire.
  228. Executing the exit procedure will cause the program control
  229. to leave the loop and begin executing the statements following
  230. the loop.
  231.  
  232. Now you have been exposed to the four loops available in
  233. Modula-2, the repeat, while, for, and loop.  Spend some time
  234.  
  235.                                                            4-4
  236.  
  237.                       Chapter 4 - Loops and Control Structures
  238.  
  239. studying this program, then compile and run it to see if it
  240. does what you expect it to do.  Loops are very important.  You
  241. will do the vast majority of your logical control in loops and
  242. if statements, so it would pay you to thoroughly understand
  243. both the loop and the if statement.
  244.  
  245.  
  246. WHAT IS AN IF STATEMENT?
  247. ______________________________________________________________
  248.  
  249. Examine the program IFDEMO.MOD for an         ================
  250. example of some IF statements in use.            IFDEMO.MOD
  251. Ignoring the header, we notice that the       ================
  252. program is composed of one big loop
  253. starting in line 10 and continuing to line 32.  This loop is
  254. included in order to have a changing variable to illustrate
  255. the use of the if statement.  Within the loop are 3 if
  256. statements.  The if statement is the most widely used
  257. conditional statement in Modula-2.
  258.  
  259. The first if statement is given in lines 11 through 15
  260. starting with the reserved word IF.  It simply says "if the
  261. value of Index1 is less than 4, then" do everything from the
  262. reserved word THEN to the reserved word END which is
  263. associated with it.  If the value of Index1 is not less than
  264. 4, then all of these statements are ignored and the next
  265. statement to be executed will be line 17 since it is the one
  266. following the reserved word END.  In a nutshell, that is all
  267. there is to the simple if statement.  Once again, the
  268. condition in line 11 can be any expression that will evaluate
  269. to a boolean result, and it can be composed of any of the
  270. simple types of data elements.
  271.  
  272.  
  273. THE ELSE CLAUSE
  274. ______________________________________________________________
  275.  
  276. The second if statement, beginning in line 17 has an added
  277. feature, the else clause.  If the boolean expression does not
  278. evaluate to true, then instead of the expressions following
  279. the reserved word THEN being executed, the group following the
  280. reserved word ELSE will be executed.  Thus, if the condition
  281. is true, everything from the THEN to the ELSE is executed, but
  282. if it is false, everything from the ELSE to the END is
  283. executed.  The end statement is therefore the terminator for
  284. the effect of the if statement.
  285.  
  286.  
  287. WHAT CAN GO IN THE IF STATEMENTS?
  288. ______________________________________________________________
  289.  
  290. You may be wondering what is allowed to go into the group of
  291. executable statements between the then and the else or between
  292. the else and the end.  The answer is, anything you want to put
  293.  
  294.                                                            4-5
  295.  
  296.                       Chapter 4 - Loops and Control Structures
  297.  
  298. there.  You can put other if statements, loops, input or
  299. output statements, calculations, just about anything.  If you
  300. indent the statements properly, you will even be able to read
  301. and understand what you put in there and why you put it there.
  302. Of course, if you put a loop in there, for example, you can
  303. put other constructs within the loop including other if
  304. statements, etc.  Thus you can go as far as you desire in
  305. building up a program.
  306.  
  307. THE ELSIF CLAUSE
  308. ______________________________________________________________
  309.  
  310.  
  311. The third and last kind of if statement is given in the third
  312. example starting on line 24 and continuing to line 30.  In
  313. this case, if the expression within the if statement is found
  314. to be false, the statements following the then are skipped and
  315. the next construct is found, the reserved word ELSIF.  If
  316. program control comes here, it has a further expression to
  317. evaluate, which if true, will cause the statements immediately
  318. following its then to be executed.  If this expression is
  319. found to be false, the statements following the else will be
  320. executed.  The net result is that, one and only one of the 3
  321. groups of instructions will be executed each time through the
  322. loop.  It is permissible to add as many elsif cases as desired
  323. to this construct, leading to a many way branch.  In addition,
  324. the else is entirely optional regardless of whether or not the
  325. elsif's are used.  After studying this program, compile and
  326. execute it and examine the result.
  327.  
  328.  
  329. LOOPs IN IFs IN LOOPs
  330. ______________________________________________________________
  331.  
  332. Load and display the next example program     ================
  333. LOOPIF.MOD for an example of some of the         LOOPIF.MOD
  334. latest topics being combined.  This           ================
  335. program makes nonsense data but is
  336. valuable because it is small enough to understand quickly to
  337. see how loops and ifs can be nested together.  The entire
  338. program is a for loop containing an if statement.  Each part
  339. of the if statement has a loop nested within it.  There is no
  340. reason why this process could not be continued if there were
  341. a need to.  Study this program, then compile and execute it.
  342.  
  343.  
  344. FINALLY, A MEANINGFUL PROGRAM
  345. ______________________________________________________________
  346.  
  347. Load and display the program named            ================
  348. TEMPCONV.MOD for your first look at a           TEMPCONV.MOD
  349. program that really does do something         ================
  350. useful.  This is a program that generates
  351. a list of temperatures in centigrade, converts the list to
  352.  
  353.                                                            4-6
  354.  
  355.                       Chapter 4 - Loops and Control Structures
  356.  
  357. fahrenheit, and displays the list along with a note in the
  358. table at the freezing point and boiling point of water.  You
  359. should have no difficulty understanding this program, so the
  360. fine points will be left up to you.
  361.  
  362. A few comments on good formatting is in order at this point.
  363. Notice the temperature conversion program and how well it is
  364. formatted.  It is simple to follow the flow of control, and
  365. the program itself needs no comments because of the judicious
  366. choice of variable names.  The block header at the top of the
  367. page is a good example of how you should get used to defining
  368. your programs.  A simple block header of that variety goes a
  369. long way toward making a program maintainable and useful
  370. later.  Take notice also of the way the variables are each
  371. defined in a comment.  A program as simple as this probably
  372. doesn't need this much attention, but it would be good for you
  373. to get into practice early.  It would be good for you to think
  374. of each of your programs as a work of art and strive to make
  375. them look good.
  376.  
  377. After spending some time studying this        ================
  378. program, compile and execute it.  Load and      DUMBCONV.MOD
  379. study the next program named DUMBCONV.MOD     ================
  380. to see if you can figure out what it does.
  381. If you are really sharp, you will very quickly see that it is
  382. the same program as the last one but without all of the extra
  383. effort to put it into a neat, easy to follow format.  Compile
  384. and execute this program and you will see that they both do
  385. the same thing.  They are identical as far as the computer is
  386. concerned.  But there is a world of difference in the way they
  387. can be understood by a human being.
  388.  
  389.  
  390. THE CASE STATEMENT
  391. ______________________________________________________________
  392.  
  393. Examine the program named CASEDEMO.MOD for    ================
  394. an example of the last decision making          CASEDEMO.MOD
  395. construct in Modula-2, the case statement.    ================
  396. A case statement is a "many-way" branch
  397. based on some simple variable.  In this program we have a loop
  398. which sets the variable named Dummy to the values from 1 to
  399. 25 successively.  Each time it comes to the case statement
  400. which begins with the reserved word CASE, one of the branches
  401. is taken.  The first branch is taken if the value is from 1
  402. to 5, the second branch is taken if the value is from 6 to 9,
  403. the third is taken if it is either a 10 or 11, etc.  Finally,
  404. if the value is not found in any of the branches, the ELSE
  405. path is taken as would be the case of a 12, a 13, or a few
  406. others.  The important point is that one and only one of the
  407. many paths are taken each time the case construct is entered.
  408. The case variable can be any of the simple types except for
  409. the real type.  For each path, as many statements can be
  410. executed as desired before the "|" is put in to end that path.
  411.  
  412.                                                            4-7
  413.  
  414.                       Chapter 4 - Loops and Control Structures
  415.  
  416. The case statement is a powerful statement when you need it
  417. but you will not use it nearly as often as you will use the
  418. if statement and the various loops.
  419.  
  420. As with all of the Modula-2 constructs, a few extra rules must
  421. be given for completeness.  The case variable can only be of
  422. a simple type, but not of a real type.  Of course the case
  423. selectors must be of the same type as the case variable and
  424. they cannot be a conditional expression, only a single value,
  425. a range, or a grouping of values as illustrated in the example
  426. program.
  427.  
  428. The example program named BIGCASE.MOD          ===============
  429. gives an additional example of a case            BIGCASE.MOD
  430. statement.  The primary difference in this     ===============
  431. case demonstration program and the last is
  432. the addition of several conditional and looping statements
  433. within the branches of the case statement.  Little or no
  434. comment is needed, so when you understand what it will do,
  435. compile and execute it.
  436.  
  437.  
  438. ONE FINAL CONTROL STRUCTURE
  439. ______________________________________________________________
  440.  
  441. At any point in the main program, you can put the reserved
  442. word RETURN, which will cause a return to the operating system
  443. when executed, effectively terminating the program.  This
  444. would probably be used as the executable statement in an if
  445. statement, but could be included in any control construct.
  446. This usage of the return statement is not illustrated in an
  447. example program in this tutorial.
  448.  
  449.  
  450. ONE MISSING CONTROL CONSTRUCT
  451. ______________________________________________________________
  452.  
  453. As mentioned earlier, there is no goto statement available in
  454. the Modula-2 programming language.  After you gain experience
  455. in using a structured language, you will not miss this
  456. construct.
  457.  
  458.  
  459.  
  460. PROGRAMMING EXERCISES
  461. ______________________________________________________________
  462.  
  463. 1.   Write a program that will put your name on the monitor
  464.      10 times using a loop.
  465.  
  466. 2.   Write a program that lists the numbers from 1 to 12 on
  467.      the monitor and prints a special message beside the
  468.      number that represents the month of your birthday.
  469.  
  470.                                                            4-8
  471.  
  472.                       Chapter 4 - Loops and Control Structures
  473.  
  474. 3.   Write a program that calculates and lists the numbers
  475.      from 1 to 8 along with the factorial of each.  This will
  476.      require use of a loop within a loop.  A factorial is the
  477.      number obtained by multiplying each number less than and
  478.      up to the number in question.  For example, factorial 4
  479.      = 1 * 2 * 3 * 4.  Use a cardinal type variable for the
  480.      result, then change it to an integer to see the
  481.      difference in output due to the range of the two
  482.      different variable types.  This is a good illustration
  483.      of the fact that careful choice of variable type is
  484.      sometimes very important.
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491.  
  492.  
  493.  
  494.  
  495.  
  496.  
  497.  
  498.  
  499.  
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.                                                            4-9
  528.  
  529.